package com.ctgu.chatapp.view.fragment.MainFragment.viewPager

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.ctgu.chatapp.databinding.FragmentFriendListByName
import com.ctgu.chatapp.showPojo.Contact
import com.ctgu.chatapp.utils.Utils
import com.ctgu.chatapp.view.adapter.ContactsAdapter
import com.ctgu.chatapp.view.adapter.DiffCallBackForFriend
import com.ctgu.chatapp.viewModel.MainViewModel
import com.gjiazhe.wavesidebar.WaveSideBar
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FriendListByName : Fragment() {

    val viewModel by lazy { ViewModelProvider(requireActivity())[MainViewModel::class.java] }

    lateinit var binding: FragmentFriendListByName

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentFriendListByName.inflate(inflater, container, false)
        binding.rvContacts.layoutManager = LinearLayoutManager(requireContext())
        initAdapter()
        binding.lifecycleOwner = requireActivity()
        return binding.root
    }

    private fun initAdapter() {
        var oldList = listOf<Contact>()
        val adapter = ContactsAdapter(
            oldList,
            viewModel.user.value!!.chatID.toInt(),
            viewModel.user.value!!.profile
        )
        binding.rvContacts.adapter = adapter
        CoroutineScope(IO).launch {
            viewModel.friendListByName.collect { it ->
                val result = DiffUtil.calculateDiff(DiffCallBackForFriend(oldList, it), true)
                oldList = it
                withContext(Main) {
                    result.dispatchUpdatesTo(adapter)
                    adapter.contacts = oldList
                    binding.sideBar.setOnSelectIndexItemListener {
                        for (i in oldList.indices) {
                            if (Utils.chineseToPinyin(oldList[i].nickName) == it) {
                                (binding.rvContacts.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(
                                    i,
                                    0
                                )
                                return@setOnSelectIndexItemListener
                            }
                        }
                    }
                }

            }
        }
        binding.sideBar.setPosition(WaveSideBar.POSITION_RIGHT)

    }
}